package com.bachongLightNovel.audit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.bachongLightNovel.audit.mapper.AuditLogsMapper;
import com.bachongLightNovel.audit.service.AuditNovelService;
import com.bachongLightNovel.constant.MessageConstant;
import com.bachongLightNovel.constant.RabbitmqConstant;
import com.bachongLightNovel.error.ErrorCodeEnum;
import com.bachongLightNovel.exception.CustomException;
import com.bachongLightNovel.model.dto.audit.AuditNovelDto;
import com.bachongLightNovel.model.pojo.audit.AuditLogs;
import com.bachongLightNovel.model.pojo.message.Message;
import com.bachongLightNovel.model.vo.audit.AuditNovelVo;
import com.bachongLightNovel.utils.UserInfoUtil;
import com.bachongLightNovel.works.IWorksNovelClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author vermouth
 */
@Service
@Slf4j
public class AuditNovelServiceImpl implements AuditNovelService {

    @Autowired
    private IWorksNovelClient worksNovelClient;

    @Autowired
    private AuditLogsMapper auditLogsMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 获取需要审核的小说列表
     * @return Result
     */
    @Override
    public List<AuditNovelVo> getAuditList(String token) {

        //调用openfeign同步接口获取所有待审核的小说信息
        List<AuditNovelVo> voList=worksNovelClient.getAuditList();
        return voList;
    }

    /**
     * 设置小说审核状态
     * @param dto :
     * @return Result
     */
    @Override
    @Transactional
    public void setAuditStatus(AuditNovelDto dto) {
        //如果是审核被驳回，需检验备注信息是否为空
        if (dto.getTargetStatus()==3 && StrUtil.isBlank(dto.getOther())){
            throw new CustomException(ErrorCodeEnum.AUDIT_NOT_PASS_INFO_EMPTY);
        }
        //调用feign接口更改novel表中的状态（需使用乐观锁进行修改）
        boolean isSuccess = worksNovelClient.setAuditStatus(dto);
        if (!isSuccess){
            throw new CustomException(ErrorCodeEnum.FEIGN_ERROR);
        }
        //添加审核日志
        Long userId = UserInfoUtil.getUser().getId();
        Long novelId = dto.getNovelId();
        AuditLogs auditLogs = new AuditLogs();
        auditLogs.setStatus((short) (dto.getTargetStatus()==2?1:0));
        auditLogs.setNovelId(novelId);
        auditLogs.setUserId(userId);
        auditLogs.setCreateTime(LocalDateTime.now());
        auditLogs.setOther(dto.getOther());
        auditLogsMapper.insert(auditLogs);
        //todo 发送异步消息，通知作者审核状态
        //调用feign，查询当前审核小说的小说名
        String novelName = worksNovelClient.getNovelNameById(dto.getNovelId());
        //封装自定义的message对象
        Message message=new Message();
        if (dto.getTargetStatus()==2){
            message.setContent(MessageConstant.MESSAGE_PASS_PREFIX+novelName+MessageConstant.MESSAGE_PASS_POSTFIX);
            message.setType((short) 1);
        }else {
            message.setContent(MessageConstant.MESSAGE_REFUSE_PREFIX+novelName+MessageConstant.MESSAGE_REFUSE_POSTFIX);
            message.setType((short) 0);
        }
        message.setTargetId(dto.getUserId());
        message.setFromId(0L);
        message.setCreateTime(LocalDateTime.now());
        message.setIsRead((short) 0);
        String jsonMessage = JSON.toJSONString(message);
        //异步发送到消息队列当中
        log.info("发送异步消息到消息交换机当中，通知审核状态：{}",jsonMessage);
        rabbitTemplate.convertAndSend(RabbitmqConstant.BACHONG_MESSAGE_EXCHANGE,
                RabbitmqConstant.BACHONG_MESSAGE_KEY,jsonMessage);
    }
}
